<template>
  <basic-dialog
    title="关联分类"
    :visible="visible"
    :show-footer="false"
    :width="'85%'"
    :handleClose="handleCloseDialog"
    :handleOpen="handleOpenDialog"
  >
    <el-row>
      <el-col :span="12" class="left-col">
        <div class="category-search">
          <el-form size="mini" ref="formData" :model="formData" inline>
            <el-form-item prop="categoryName" label="名称">
              <el-input
                placeholder="请输入品类名称"
                v-model="formData.categoryName"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item prop="categoryName" label="编码">
              <el-input
                placeholder="请输入四级类编码"
                v-model="formData.categoryNo"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSerach">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="divider" content-position="left">条件查询结果：</el-divider>
        <div class="category-searchlist">
          <el-checkbox-group v-model="searchList.checkList">
            <el-checkbox
              v-for="item in searchList.dataSource"
              :label="item.categoryUuid"
              :key="item.categoryUuid"
              @change="(val) => { handleCheckSearchList(val, item) }"
            >
            {{ item.categoryPath }}&nbsp;&nbsp;{{ item.categoryNo }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-divider class="divider" content-position="left">品类树选择：</el-divider>
        <div class="category-tree">
          <el-tree
            ref="elTree"
            lazy
            accordion
            show-checkbox
            :node-key="elTree.nodeKey"
            :data="elTree.dataSource"
            :props="elTree.props"
            :load="loadElTreeNode"
            @check="getCheckedNodes"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="selected-card">
          <ResultHeader
            ref="resultHeaderRef"
            :result-list="this.selectCategoryList"
            :confirm-loading="loadingInstance.submit"
            @confirm="handleSubmit"
            @clear="handleClear"
            @senior="updateResultListBySeniorSearch"
          />
          <el-divider class="divider" />
          <el-tag
            v-loading="loadingInstance.result"
            class="category-tag"
            v-for="tag in selectCategoryList"
            :key="tag.categoryUuid"
            closable
            :disable-transitions="false"
            effect="plain"
            @close="handleRemoveCategory(tag, true)">
            <span class="tag-text">{{tag.categoryPath}} {{tag.categoryNo}}</span>
          </el-tag>
        </div>
      </el-col>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import ResultHeader from '@/components/Category/AllLevelMultipleSelect/ResultHeader';
import { isResponseSuccess } from '@/utils/bizUtils';
import {
  getByCategoryNameService,
  getByParentUuidsService,
  getcategoryUuidsByLabelUuidService,
  createRelateLabelService
} from '@/api/commodity/commodityManage/productTagManage'
import { getFullPathByUuidsService } from '@/api/public';

export default {
  name: 'LinkCategoryDialog',
  components: {
    BasicDialog,
    ResultHeader
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    labelUuid: {
      type: String | Number,
      default: ''
    }
  },
  data () {
    return {
      selectCategoryList: [], // 已选品类集合
      searchCategoryList: [], // 条件查询选择集合
      treeCategoryList: [], // 品类树选择集合
      elTree: {
        dataSource: [], // 数据源
        props: {
          children: 'children',
          label: 'cateNameAndNoStr',
          disabled: 'disabled',
          isLeaf: 'leaf',
          checked: false
        },
        nodeKey: 'categoryNo',
        END_LEVEL: '4',
      },
      formData: {
        categoryName: '',
        categoryNo: '',
      },
      searchList: { // 查询列表
        dataSource: [], // 数据源
        checkList: [], // 勾选对象
      },
      loadingInstance: {
        submit: false,
        tree: false,
        result: false
      }
    };
  },
  watch: {
    searchCategoryList: {
      handler (val) {
        this.generateLinkData()
      },
      deep: true
    },
    treeCategoryList: {
      handler (val) {
        this.generateLinkData()
      },
      deep: true
    },
  },
  methods: {
    // 更新高级关联结果集合
    async updateResultListBySeniorSearch (categroyUuidList) {
      const data = { categroyUuidList }
      const loadingFn = state => { this.loadingInstance.result = state }
      const res = await getFullPathByUuidsService(data, loadingFn)
      const concatList = [...this.selectCategoryList, ...res?.retData ?? []].map(item => ({
        ...item,
        categoryPath: item.fullNames,
        categoryUuid: item.uuid
      }))
      this.selectCategoryList = _.uniqBy(concatList, this.elTree.nodeKey)
      this.treeCategoryList = [...this.selectCategoryList]
    },
    // 表单-分类名称查询
    handleSerach () {
      const { categoryNo, categoryName } = this.formData ?? {}
      if (!categoryNo && !categoryName) return this.$message.warning('品类名称和品类编码不能同时为空')
      this.setSearchCategoryResults()
    },
    // 设置分类查询结果
    async setSearchCategoryResults () {
      const data = { ...this.formData }
      const res = await getByCategoryNameService(data, '.category-searchlist')
      if (res?.retData) {
        this.searchList.checkList = [];
        this.searchList.dataSource = res.retData;
      }
    },
    // 查询已关联分类
    async getSelectedCategory () {
      const data = { labelUuid: this.labelUuid }
      const res = await getcategoryUuidsByLabelUuidService(data, '.selected-card')
      if (res?.retData) {
        this.selectCategoryList = res.retData.map(item => ({
          ...item,
          categoryPath: item.fullNames,
          categoryUuid: item.uuid
        }))
        this.treeCategoryList = [...this.selectCategoryList]
      }
    },
    // 获取分类树集合
    async getCategoryTreeList (data) {
      const loadingFn = state => { this.loadingInstance.tree = state }
      const res = await getByParentUuidsService(data, loadingFn)
      return res
    },
    // 查询一级分类
    async getLevelOneCategoryList () {
      const res = await this.getCategoryTreeList(['systemUuid'])
      if (res?.retData) {
        this.elTree.dataSource = this.formatElTreeData(res.retData)
      }
    },
    // 加载el-tree节点
    async loadElTreeNode (node, resolve) {
      if (node.level === 0) return
      const { categoryUuid } = node.data;
      const res = await this.getCategoryTreeList([categoryUuid])
      if (res?.retData) resolve(this.formatElTreeData(res.retData))
    },
    // 格式化el-tree数据
    formatElTreeData (list = []) {
      return list.map(item => ({
        ...item,
        disabled: ['1', '2', '3'].includes(item.levelNum),
        leaf: item.levelNum === this.elTree.END_LEVEL
      }));
    },
    // 勾选分类查询结果列表
    handleCheckSearchList (val, data) {
      if (!val) return this.handleRemoveCategory(data)
      const hasCate = this.searchCategoryList.some(item => item.categoryUuid == data.categoryUuid)
      !hasCate && this.searchCategoryList.push(data)
    },
    // 取消品类选择
    handleRemoveCategory (data, isTag) {
      this.searchCategoryList = this.searchCategoryList.filter(item => item.categoryUuid != data.categoryUuid)
      this.treeCategoryList = this.treeCategoryList.filter(item => item.categoryUuid != data.categoryUuid)
      if (isTag) {
        this.searchList.checkList = this.searchList.checkList.filter(item => item != data.categoryUuid)
        this.$refs.elTree.setChecked(data[this.elTree.nodeKey], false);
      }
    },
    // 勾选树节点
    async getCheckedNodes (current, checkedData) {
      const { checkedNodes } = checkedData;
      const level4List = checkedNodes.filter(item => item.levelNum == 4)
      this.treeCategoryList = _.uniqBy(level4List.concat([]), this.elTree.nodeKey)
    },
    // 清空选择结果
    handleClear () {
      this.$confirm('确定后将清空所有已选四级分类，您确认吗？', '清空', {
        type: 'warning',
      }).then(() => {
        this.handleClearCategory()
      }).catch(() => {});
    },
    // 清空所有已勾选节点的勾选状态
    clearAllCheckedNodes () {
      this.$refs.elTree.setCheckedKeys([]); // 全部取消el-tree勾选节点
    },
    // 关闭所有已展开节点
    closeAllExpandNodes () {
      var nodes = this.$refs.elTree.store.nodesMap;
      for (let i in nodes) {
        nodes[i].expanded = false;
      }
    },
    // 组合已关联数据
    generateLinkData () {
      this.selectCategoryList = _.uniqBy(
        [
          ...this.searchCategoryList,
          ...this.treeCategoryList,
        ],
        this.elTree.nodeKey
      )
    },
    // 提交
    async handleSubmit () {
      const data = {
        cateUuids: this.selectCategoryList.map(item => item.categoryUuid).join(','),
        labelUuid: this.labelUuid
      }
      const loadingFn = state => { this.loadingInstance.submit = state }
      const res = await createRelateLabelService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.handleCloseDialog()
      }
    },
    // 清空弹框内容
    handleClearCategory () {
      this.searchCategoryList = [];
      this.treeCategoryList = [];
      this.searchList.checkList = [];
      this.clearAllCheckedNodes();
      this.closeAllExpandNodes();
      this.searchList.dataSource = [];
      this.$refs.formData.resetFields()
      this.$refs.resultHeaderRef?.clearSeniorLinked() // 清空高级关联内容
    },
    // 打开弹窗
    handleOpenDialog () {
      this.getLevelOneCategoryList();
      this.getSelectedCategory();
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:visible', false);
      this.handleClearCategory()
    },
  }
};
</script>
<style lang="less" scoped>
.divider {
  margin: 10px 0;
}
.left-col {
  border-right: 1px dashed #dadada;
  padding-right: 20px;
}
.category-searchlist {
  .el-checkbox-group {
    border: 1px solid #ebeef5;
    padding-left: 5px;
    height: 200px;
    max-height: 200px;
    overflow-y: auto;
    label {
      line-height: 24px;
      &:first-child {
        margin-top: 10px;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
  }
}
/deep/ .category-tree {
  height: 400px !important;
  overflow: auto;
  margin: 10px 0px;
  border: 1px solid #ebeef5;
}
.category-tag {
  margin: 5px 0;
  .tag-text {
    display: inline-block;
    width: 440px;
    /* overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis; */
  }
}
.selected-card {
  padding: 10px;
  // border: 1px solid #ebeef5;
  margin-left: 10px;
  max-height: 700px;
  overflow: auto;
}
</style>
